package com.dc.wifi.main.utils;


import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;

import com.dc.wifi.R;

import android.content.Context;
import android.media.MediaPlayer;

public class AudioPlayer {

    private Context context;
    private MediaPlayer mediaPlayer;
    private int currentFrequencyMillis;

    public AudioPlayer(Context context) {
        this.context = context;
        this.mediaPlayer = MediaPlayer.create(context, R.raw.zzzz);
        this.currentFrequencyMillis = 2000; // Default frequency: 2 seconds
    }

    // Method to start playing audio with current frequency
    public void play() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            startLoop();
        }
    }

    // Method to stop playing audio
    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
        }
    }

    // Method to set playback frequency (interval in seconds)
    public void setFrequency(float seconds) {
        currentFrequencyMillis = (int) (seconds * 1000);
    }

    // Internal method to start a loop for repeating playback at current frequency
    private void startLoop() {
        if (mediaPlayer != null) {
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.start(); // Restart playback
                    mp.seekTo(0); // Reset position to start
                    mp.setOnCompletionListener(this); // Set listener to loop
                }
            });
            mediaPlayer.start();
        }
    }

    // Release resources when done using the AudioPlayer
    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}